package cn.maydaymemory.maydaycore;

import cn.maydaymemory.maydaycore.command.api.*;
import cn.maydaymemory.maydaycore.command.Example;
import cn.maydaymemory.maydaycore.configuration.LanguageManager;
import cn.maydaymemory.maydaycore.loader.LibsLoader;
import jdk.nashorn.api.scripting.URLReader;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.java.JavaPlugin;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;

public class PluginMaydayCore extends JavaPlugin {

    private LanguageManager lang;
    private static PluginMaydayCore instance;
    {
        instance=this;
    }
    private static final String mddlURL ="https://maydaycore-1301265549.cos.ap-nanjing.myqcloud.com/MaydayCore-AetherAPI.jar";


    private static boolean downloadMDDL(){
        Bukkit.getServer().getLogger().info("[MaydayCore]未找到MaydayCore-AetherAPI，尝试从指定URL获取文件。");
        try {
            URL httpUrl=new URL(mddlURL);
            HttpURLConnection conn=(HttpURLConnection) httpUrl.openConnection();
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.connect();
            File jarFile = new File("plugins\\MaydayCore\\download\\MaydayCore-AetherAPI.jar");
            InputStream inputStream=conn.getInputStream();
            FileOutputStream fileOut = new FileOutputStream(jarFile);
            BufferedInputStream bis = new BufferedInputStream(inputStream);
            BufferedOutputStream bos = new BufferedOutputStream(fileOut);
            Bukkit.getServer().getLogger().info("   正在下载MaydayCore-AetherAPI...");
            Bukkit.getServer().getLogger().info("   可能需要一段时间，请耐心等待。");
            byte[] buf = new byte[4096];
            int length = bis.read(buf);
            while(length > -1)
            {
                bos.write(buf, 0, length);
                length = bis.read(buf);
            }
            bos.close();
            bis.close();
            conn.disconnect();
            return jarFile.renameTo(new File("plugins\\MaydayCore\\libs\\MaydayCore-AetherAPI.jar"));
        } catch (MalformedURLException e) {
            Bukkit.getServer().getLogger().warning("[MaydayCore]URL地址格式错误。");
        } catch (IOException e) {
            Bukkit.getServer().getLogger().warning("[MaydayCore]MaydayCore-AetherAPI下载失败。");
            e.printStackTrace();
        }
        return false;
    }

    private static Map<String, List<String>> getThreeDimensional(){
        Map<String, List<String>> map = new HashMap<>();
        File[] files = new File("plugins\\").listFiles();
        for(File file :  files){
            if(file.isDirectory()) continue;
            if(!file.getName().substring(file.getName().lastIndexOf(".")).equals(".jar")) continue;
            try {
                URL url=new URL("jar:file:plugins/"+file.getName()+"!/plugin.yml");
                YamlConfiguration config = YamlConfiguration.loadConfiguration(new URLReader(url));
                if(config==null) continue;
                List<String> strs = config.getStringList("maven-dependence");
                if(strs==null||strs.isEmpty()) continue;
                map.put(config.getString("name"),strs);
            } catch (MalformedURLException | NullPointerException ignore) {  }
        }
        return map;
    }

    static {
        File libs =new File("plugins\\MaydayCore\\libs\\");
        File download =new File("plugins\\MaydayCore\\download\\");
        if(!download.exists()) download.mkdirs();
        File mddl = new File(libs,"MaydayCore-AetherAPI.jar");
        if((!libs.exists()&&libs.mkdirs())||libs.exists()) {
            if((!mddl.exists()&&downloadMDDL())||mddl.exists()) {
                try {
                    LibsLoader.loadJars(libs);
                    Class.forName("cn.maydaymemory.maydaycore.MavenDependenceDownloader");

                    Map<String,List<String>> wants = getThreeDimensional();
                    for(String key: wants.keySet()){
                        for(String td: wants.get(key)){
                            td = td.replaceAll(" ","");
                            String[] pars = td.split(";");
                            if(pars.length<3) continue;
                            String repository = null;
                            if(pars.length>=4) repository=pars[3];
                            Bukkit.getServer().getLogger().info("[MaydayCore] 正在为插件:"+key+" 加载依赖: "+td);
                            if(repository!=null) MavenDependenceDownloader.DownLoad(
                                                     new MavenDependenceDownloader.Params(pars[0], pars[1], pars[2])
                                                             .setRepository(repository)
                                                             .setTarget(libs.toString())    );
                            else MavenDependenceDownloader.DownLoad(
                                    new MavenDependenceDownloader.Params(pars[0], pars[1], pars[2])
                                            .setTarget(libs.toString())    );
                        }
                    }

                    LibsLoader.loadJars(libs);
                } catch (ClassNotFoundException e) {
                    Bukkit.getServer().getLogger().warning("§c找不到MaydayCore-AetherAPI,无法从远程仓库拉取依赖。");
                } catch (Exception e) {
                    Bukkit.getServer().getLogger().warning("Maven依赖下载失败");
                }
            }
        }
    }

    @Override
    public void onEnable(){
        lang=new LanguageManager(this);
        lang.preload(Locale.getDefault());
        lang.preloadDefault();
        SuperCommand command = new SuperCommand("MaydayCore",new Example());
        List<String> aliases = new ArrayList<>();
        aliases.add("mc");
        aliases.add("mcore");
        command.setAliases(aliases);
        CommandManager.register(command);
    }
    public LanguageManager getLanguage(){
        return lang;
    }
    public static PluginMaydayCore getInstance(){return instance;}
}
